from hackprofile.models import ForumProfile, Hacker
from django import template

register = template.Library()


class ForumProfileNode(template.Node):
    def __init__(self, uservar, varname):
        self.user_var = template.Variable(uservar)
        self.varname = varname
    
    def render(self, context):
        try:
            actual_user = self.user_var.resolve(context)
            profile = ForumProfile.objects.get(user=actual_user)
        except template.VariableDoesNotExist, ForumProfile.DoesNotExist:
            return ''
        context[self.varname] = profile
        return ''

        
@register.tag
def get_forum_profile(parser, token):
    """Usage: {% get_forum_profile user as var_name %}"""
    try:
        tag_name, user, as_keyword, varname = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError("Incorrect usage of %r tag" % token.contents.split()[0])
    return ForumProfileNode(uservar, varname)
    
    
